package com.zidian.study.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.youth.banner.loader.ImageLoader;
import com.yuyh.library.imgsel.ImgSelActivity;
import com.yuyh.library.imgsel.ImgSelConfig;
import com.zidian.study.bean.UserMessageBean;
import com.zidian.study.event.StudentInfoChangeEvent;
import com.zidian.study.globa.BaseEntity;
import com.zidian.study.globa.Constant;
import com.zidian.study.globa.ToolBarActivity;
import com.zidian.study.utils.BottomDialogAdapter;
import com.zidian.study.utils.BottomDialogEntity;
import com.zidian.study.utils.CameraPicTureUtil;
import com.zidian.study.utils.CommonDialogUtil;
import com.zidian.study.utils.GetUserInfo;
import com.zidian.study.utils.ProgressBarBlackUtil;
import com.zidian.study.utils.StringHelper;
import com.zidian.study.utils.ToastUtil;
import com.zidian.study.view.GlideImageLoader;
import com.zidian.study.wheel.NumericWheelAdapter;
import com.zidian.study.wheel.WheelView;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import com.zidian.student.trucks.R;

/**
 * Created by Administrator on 2016/8/27 0027.
 * <p/>
 * 修改个人信息
 */
public class StudyChangeActivity extends ToolBarActivity {

    @Bind(R.id.study_image_change)
    CircleImageView studyImageChange;
    @Bind(R.id.study_change_nick_name)
    EditText studyChangeNickName;
    @Bind(R.id.study_change_sex)
    TextView studyChangeSex;
    @Bind(R.id.study_change_birthday)
    TextView studyChangeBirthday;
    @Bind(R.id.study_change_age)
    TextView studyChangeAge;
    @Bind(R.id.study_change_phone)
    EditText studyChangePhone;
    @Bind(R.id.study_change_personalized_signature)
    EditText studyChangePersonalizedSignature;
    @Bind(R.id.submit_btn)
    TextView submitBtn;

    private static final int REQUEST_CODE = 0;

    public AlertDialog genderTalkDialog;
    public AlertDialog mDialogView;
    public UserMessageBean studyMessage = new UserMessageBean();

    private WheelView year;
    private WheelView month;
    private WheelView day;

    private int mYear = 1996;
    private int mMonth = 0;
    private int mDay = 1;
    private TextView mBtnDateConfirm;
    private TextView mBtnCancel;

    private boolean isFirst = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolbarView(R.layout.toolbar_left);
        setContentView(R.layout.activity_study_message_change);
        setTitle("编辑个人资料");
        ButterKnife.bind(this);
        Intent intent = this.getIntent();
        studyMessage = (UserMessageBean) intent.getSerializableExtra("studyMessage");
        initView();
    }

    public void initView() {
        if (studyMessage.getData() != null) {
            studyChangeNickName.setText(studyMessage.getData().getMyNickName());
            studyChangeSex.setText(studyMessage.getData().getStudentSex());
            studyChangeBirthday.setText(studyMessage.getData().getMyBirthd());
            studyChangeAge.setText(studyMessage.getData().getStudentAge());
            studyChangePhone.setText(studyMessage.getData().getStudentPhoneNumber());
            studyChangePersonalizedSignature.setText(studyMessage.getData().getPersonalizedSignature());
            Glide.with(context)
                    .load(studyMessage.getData().getStudentHeadPortrait())
                    .centerCrop()
                    .into(studyImageChange);
        }

        submitBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (isFirst) {
                    isFirst = false;
                    try {
                        setMessage();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }


            }
        });


        studyChangeBirthday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                clickBirthday();
            }
        });
        studyChangeSex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickGender();
            }
        });

    }

    /**
     * 加载本地图片
     * http://bbs.3gstdy.com
     *
     * @param url
     * @return
     */
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }



    /**
     * 性别的点击方法
     */

    private void clickGender() {
        genderTalkDialog = CommonDialogUtil.getBottomDialog(context);
        Window window = genderTalkDialog.getWindow();
        ListView dialogListView = (ListView) window
                .findViewById(R.id.dialogListView);
        ArrayList<BottomDialogEntity> bottomDialogEntities = new ArrayList<>();
        bottomDialogEntities.add(new BottomDialogEntity("0", "男"));
        bottomDialogEntities.add(new BottomDialogEntity("1", "女"));

        BottomDialogAdapter adapter = new BottomDialogAdapter(context,
                bottomDialogEntities);
        dialogListView.setAdapter(adapter);

        dialogListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapter, View view,
                                    int position, long id) {

                setGender(position);

            }
        });

    }

    private void setGender(int position) {
        // 设置性别
        switch (position) {
            case 0:
                studyChangeSex.setText("男");
                genderTalkDialog.dismiss();
                break;

            case 1:
                studyChangeSex.setText("女");
                genderTalkDialog.dismiss();
                break;

            default:
                break;
        }

    }


    /**
     * 生日的点击方法
     */
    private void clickBirthday() {
        mDialogView = CommonDialogUtil.getCommonDialog(context,
                R.layout.study_birthday, Gravity.BOTTOM);

        year = (WheelView) mDialogView.findViewById(R.id.id_province);
        month = (WheelView) mDialogView.findViewById(R.id.id_city);
        day = (WheelView) mDialogView.findViewById(R.id.id_district);
        mBtnDateConfirm = (TextView) mDialogView.findViewById(R.id.btn_confirm);
        mBtnCancel = (TextView) mDialogView.findViewById(R.id.btn_cancel);
        mBtnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialogView.dismiss();
            }
        });
        mBtnDateConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSelectedResult();
            }
        });
        setUpDataDate();
    }

    /**
     * 更新日期数据
     **/
    private void setUpDataDate() {
        getDataPick();
        year.setVisibleItems(7);
        month.setVisibleItems(7);
        day.setVisibleItems(7);
    }


    /**
     * 初始化日期的数据
     */
    private void getDataPick() {
        Calendar c = Calendar.getInstance();
        int norYear = c.get(Calendar.YEAR);

        int curYear = mYear;
        int curMonth = mMonth + 1;
        int curDate = mDay;

        NumericWheelAdapter numericWheelAdapter1 = new NumericWheelAdapter(
                this, 1950, norYear);
        numericWheelAdapter1.setLabel("年");
        year.setViewAdapter(numericWheelAdapter1);
        year.setCyclic(true);

        NumericWheelAdapter numericWheelAdapter2 = new NumericWheelAdapter(
                this, 1, 12, "%02d");
        numericWheelAdapter2.setLabel("月");
        month.setViewAdapter(numericWheelAdapter2);
        month.setCyclic(true);

        initDay(curYear, curMonth);
        day.setCyclic(true);

        year.setCurrentItem(curYear - 1950);
        month.setCurrentItem(curMonth - 1);
        day.setCurrentItem(curDate - 1);

    }

    /**
     * 得到当个月的天数
     *
     * @param year
     * @param month
     * @return
     */
    private int getDay(int year, int month) {
        int day = 30;
        boolean flag = false;
        switch (year % 4) {
            case 0:
                flag = true;
                break;
            default:
                flag = false;
                break;
        }
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                day = 31;
                break;
            case 2:
                day = flag ? 29 : 28;
                break;
            default:
                day = 30;
                break;
        }
        return day;
    }

    /**
     * 初始化日期
     */
    private void initDay(int arg1, int arg2) {
        NumericWheelAdapter numericWheelAdapter = new NumericWheelAdapter(this,
                1, getDay(arg1, arg2), "%02d");
        numericWheelAdapter.setLabel("日");
        day.setViewAdapter(numericWheelAdapter);
    }

    /**
     * 显示最后的时间和地址的结果
     */
    private void showSelectedResult() {

        int n_year = year.getCurrentItem() + 1950;
        int n_month = month.getCurrentItem() + 1;
        initDay(n_year, n_month);
        String birthday = new StringBuilder()
                .append((year.getCurrentItem() + 1950))
                .append("-")
                .append((month.getCurrentItem() + 1) < 10 ? "0"
                        + (month.getCurrentItem() + 1) : (month
                        .getCurrentItem() + 1))
                .append("-")
                .append(((day.getCurrentItem() + 1) < 10) ? "0"
                        + (day.getCurrentItem() + 1) : (day
                        .getCurrentItem() + 1)).toString();
        mDialogView.dismiss();
        studyChangeBirthday.setText(birthday);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
        int currentYear =Integer.parseInt(dateFormat.format(new Date()));
        studyChangeAge.setText(currentYear - n_year + "");

    }

    @OnClick(R.id.study_image_change)
    public void changeStudentImage(){
        pickImages();
    }

    /**
     * 图片加载器
     */
    private com.yuyh.library.imgsel.ImageLoader loader = new com.yuyh.library.imgsel.ImageLoader() {
        @Override
        public void displayImage(Context context, String path, ImageView imageView) {
            Glide.with(context).load(path).into(imageView);
        }
    };

    /**
     * 图片选择器
     */
    private void pickImages() {
        ImgSelConfig config = new ImgSelConfig.Builder(loader)
                // 是否多选
                .multiSelect(false)
                // 确定按钮背景色
                .btnBgColor(Color.GRAY)
                // 确定按钮文字颜色
                .btnTextColor(Color.BLUE)
                // 使用沉浸式状态栏
//                .statusBarColor(Color.parseColor("#3F51B5"))
                // 返回图标ResId
                .backResId(android.support.v7.appcompat.R.drawable.abc_ic_ab_back_mtrl_am_alpha)
                .title("图片")
                .titleColor(Color.WHITE)
                .titleBgColor(Color.parseColor("#25bf7f"))
                .cropSize(1, 1, 100, 100)
                .needCrop(true)
                // 第一个是否显示相机
                .needCamera(true)
                .build();

        ImgSelActivity.startActivity(this, config, REQUEST_CODE);
    }
    /**
     * Activity返回信息
     **/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null) {
            List<String> pathList = data.getStringArrayListExtra(ImgSelActivity.INTENT_RESULT);

            Glide.with(context).load(pathList.get(0)).into(studyImageChange);
            try {
                setImage(pathList.get(0));
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }


    /**
     * 修改学生头像
     *
     * @param path
     * @throws IOException
     */
    public void setImage(String path) throws IOException {
        String loginUrl = Constant.URL_GOAL + "studentApp/updMe";
        HashMap map = new HashMap();
        map.put("studentId", GetUserInfo.getStudentId(context));
        map.put("token", GetUserInfo.getToken(context));

        ProgressBarBlackUtil.loadShow(context);
        OkHttpUtils.post().
                url(loginUrl).
                addFile("studentHeadPortrait", StringHelper.getImageName(path), new File(path)).params(map).
                build().
                connTimeOut(20000).
                writeTimeOut(20000).
                readTimeOut(20000).
                execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        isFirst = true;
                        ProgressBarBlackUtil.loadCancel();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        isFirst = true;
                        Gson gson = new Gson();
                        BaseEntity base = gson.fromJson(response, BaseEntity.class);
                        if (base.isSuccess()) {
                            ProgressBarBlackUtil.loadCancel();
                            Snackbar.make(submitBtn,"更换头像成功!",Snackbar.LENGTH_SHORT).show();
                            EventBus.getDefault().post(new StudentInfoChangeEvent(true));
                        }
                    }
                });
    }

    /**
     * 修改学生个人信息
     *
     * @throws IOException
     */
    private void setMessage() throws IOException {
        String loginUrl = Constant.URL_GOAL + "studentApp/updMe";
        HashMap map = new HashMap();
        map.put("studentId", GetUserInfo.getStudentId(context));
        map.put("token", GetUserInfo.getToken(context));
        map.put("personalizedSignature", studyChangePersonalizedSignature.getText().toString().trim());
        map.put("studentPhoneNumber", studyChangePhone.getText().toString().trim());
        map.put("studentSex", studyChangeSex.getText().toString().trim());
        map.put("myBirthd", studyChangeBirthday.getText().toString().trim());
        map.put("myNickName", studyChangeNickName.getText().toString().trim());
        ProgressBarBlackUtil.loadShow(context);
        OkHttpUtils.post().url(loginUrl).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                isFirst = true;
                Log.e("E", e.toString());
                ProgressBarBlackUtil.loadCancel();
            }

            @Override
            public void onResponse(String response, int id) {
                isFirst = true;
                Gson gson = new Gson();
                BaseEntity base = gson.fromJson(response, BaseEntity.class);
                if (base.isSuccess()) {
                    ProgressBarBlackUtil.loadCancel();
                    ToastUtil.showToast(context, "提交成功");
                    EventBus.getDefault().post(new StudentInfoChangeEvent(true));
                    finish();
                }
            }
        });

    }


}
